<?php


namespace app\admin\controller;


use app\common\service\ProcessService;
use app\common\service\QueueService;
use think\Console;
use think\Db;

class Queue extends Base
{
    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'SystemQueue';

    public function index()
    {
        $message = Console::call('api:queue', ['status'])->fetch();
        $this->assign('command', (new ProcessService())->think('api:queue start'));
        $this->assign('message', $message);
        $this->assign('listen', preg_match('/process.*?\d+.*?running/', $message, $attr));
        // 任务状态统计
        $total = ['dos' => 0, 'pre' => 0, 'oks' => 0, 'ers' => 0];
        $query = Db::name($this->table)->field('status,count(1) count');
        foreach ($query->group('status')->select() as $item) {
            if ($item['status'] === 1) $total['pre'] = $item['count'];
            if ($item['status'] === 2) $total['dos'] = $item['count'];
            if ($item['status'] === 3) $total['oks'] = $item['count'];
            if ($item['status'] === 4) $total['ers'] = $item['count'];
        }
        $this->assign('total', $total);

        $this->assign('list', Db::name($this->table)->order('loops_time desc,id desc')->select());


        return $this->fetch('queue/index');
    }


    public function progress()
    {
        $code = input('code');
        if ($code) {
            $queue = (new  QueueService())->initialize($code);
            return json(['data' => $queue->progress(), 'code' => 1, 'info' => '获取任务进度成功']);
        } else {
            $this->error('任务编号不能为空');
        }
    }


    /**
     * 重启系统任务
     * @auth true
     */
    public function redo()
    {
        $code = input('code');
        if ($code) {
            $queue = (new  QueueService())->initialize($code)->reset();
            $queue->progress(1, '>>> 任务重置成功 <<<', 0.00);
            $this->success('任务重置成功！', $queue->code);
        } else {
            $this->error('任务编号不能为空');
        }
    }


    /**
     * 删除系统任务
     * @auth true
     * @throws DbException
     */
    public function remove()
    {
        Db::name($this->table)->where('id', input('id'))->delete();
        $this->success('删除成功');
    }
}